package com.imoblife.brainwavestus.util;

import java.util.ArrayList;

import android.content.Context;

import com.imoblife.brainwavestus.model.Constant;
import com.imoblife.brainwavestus.newdownloadframe.DownLoadTaskInfo;
import com.imoblife.brainwavestus.oldDownloadFrame.Commmand;
import com.imoblife.brainwavestus.product.Product;
import com.imoblife.brainwavestus.product.ProductInfo;
import com.imoblife.brainwavestus.product.Store;
import com.imoblife.brainwavestus.service.DownLoadSchedulerSystem;

public class DownloadUtil {

	public static void beginDownloadProduct(Context ctx, Store store,
			String productId) {
		
		DebugUtil.debug("DownloadUtil", "beginDownloadProduct ~");
		
		Product product = store.getProductByName(productId);
		ProductInfo info = product.getProductInfo();

		ArrayList<ProductInfo> infos = new ArrayList<ProductInfo>();

		DBUtil db = new DBUtil(ctx);

		db.openForWrite();

		if (info.isProductCollection()) {

			ArrayList<Product> products = product.getAllChild();

			for (Product item : products) {

				infos.add(item.getProductInfo());
			}
		} else {

			infos.add(info);
		}

		for (ProductInfo infoItem : infos) {
			
			DebugUtil.debug("downloadUtil",
					"downstate: " + infoItem.getDownloadState()
					+ "info name: " + infoItem.getName());
			if (infoItem.getDownloadState().equals(
					Constant.DOWNLOAD_STATE_NOT_ENBLE)) {

				infoItem.setDownloadState(Constant.DOWNLOAD_STATE_START);
				
				String changeTime = ProductUtil.long2String(System
											.currentTimeMillis());
				infoItem.setChangeTime(changeTime);
				db.openForWrite().updateProduct(infoItem);
				db.closeDb();
				
				String downTaskName = infoItem.getId() + Constant.MUSIC_FILE_SUFFIX;
				store.addDownloadTaskToStack(downTaskName);
				
				DownLoadTaskInfo downInfo = new DownLoadTaskInfo();
				
				downInfo.setChangeTime(changeTime);
				downInfo.setTaskName(downTaskName);
				downInfo.setState(Constant.INT_DOWN_STATE_START);
				downInfo.setLevel(DownLoadSchedulerSystem.LEVEL_MUSIC);
				
				long row = db.openForWrite().insertNewDownTask(downInfo);
				
				DebugUtil.dbDebug("DownloadUtil", "insert down task row:" + row);
				db.closeDb();
				
				//user.addDownTask(downInfo);
			}
		}
		
		String firstDownloadTask = db.openForRead().getHighestLevelDownTask();	
		db.closeDb();
		
		DebugUtil.debug("DownloadUtil", "firstDownloadTask:" + firstDownloadTask);
		
		if (firstDownloadTask != null) {

			Commmand.makeMusicDownloadCommand(firstDownloadTask, ctx);
			
			DebugUtil.debug("DownloadUtil", "send download command");
		}
	}
}
